package com.datastructure.test.rotatelinkedlist;

public class RotateLinkedList {

    public static void main(String[] args) {

    }

    public ListNode rotateLinkedList (ListNode head, int k) {
        // write code here
        if(head==null){
            return head;
        }
        int listNodeLength = getListNodeLength(head);
        k%=listNodeLength;
        if(0==k||listNodeLength==1){
            return head;
        }
        int index = 0;
        ListNode first=head;
        ListNode lastListNode=head;
        ListNode lastLastListNode=head;
        ListNode lastLastLastListNode=head;
        while (head!=null){
            index++;
            if(index==1){
                first=head;
            }
            if(index==listNodeLength-k){
                lastListNode=head;
                lastLastListNode=lastListNode.next;
            }
            if(index==listNodeLength){
                lastLastLastListNode=head;
            }
            head=head.next;
        }
        lastListNode.next=null;
        lastLastLastListNode.next=first;
        return lastLastListNode;
    }

    public int getListNodeLength(ListNode head){
        int num = 0;
        while (head!=null){
            num++;
            head=head.next;
        }
        return num;
    }
}
class ListNode {
   int val;
   ListNode next = null;
   public ListNode(int val) {
     this.val = val;
   }
 }
